package com.grey_zoo.lottery.presenter;

import ZhongXinFenPai.TCallback;
import ZhongXinFenPai.TEvent;
import ZhongXinFenPai.TIntent;
import ZhongXinFenPai.TObserver;
import android.app.Application;
import android.os.Handler;
import android.widget.ImageView;

import com.grey_zoo.lottery.R;
import com.grey_zoo.lottery.event.ImageLoaderEvent;
import com.grey_zoo.lottery.global.GlobalValue;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;

public class ImageLoaderEventManager implements TObserver {

	public Application application;
	public static ImageLoaderEventManager immanager = new ImageLoaderEventManager();

	public ImageLoaderEventManager() {
		RegisterEvent();

	}

	@Override
	public void onEvent(TEvent event, TCallback callback)
			throws NoSuchMethodException, Exception, Exception {
		// TODO Auto-generated method stub

		final ImageLoaderEvent imageevent = (ImageLoaderEvent) event;
		switch (imageevent.flat) {
		case 0:
			initimageloader();
			break;
		case 1:
			(GlobalValue.activity).runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					disply(imageevent.url, imageevent.imageview, option());
				}
			});

		default:
			break;

		}

	}

	public void initimageloader() {

		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				GlobalValue.application).build();

		ImageLoader.getInstance().init(config);

		GlobalValue.imageLoader = ImageLoader.getInstance();

	}

	public void RegisterEvent() {

		TIntent.getInstance().registerEvent(ImageLoaderEvent.class, this);

	}

	public static ImageLoaderEventManager getInstance() {
		return immanager;

	}

	public DisplayImageOptions option() {

		DisplayImageOptions options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.ic_launcher) // resource or
				// drawable
				.showImageForEmptyUri(R.drawable.ic_launcher) // resource or
				// drawable
				.showImageOnFail(R.drawable.ic_launcher) // resource or
				// drawable
				.resetViewBeforeLoading(false) // default
				.delayBeforeLoading(1000).cacheInMemory(true) // default
				.cacheOnDisk(true) // default
				.considerExifParams(false) // default
				.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
				.displayer(new SimpleBitmapDisplayer()) // default
				.handler(new Handler()) // default
				.build();

		return options;
	}

	public void disply(String url, ImageView image, DisplayImageOptions options) {
		GlobalValue.imageLoader.displayImage(url, image, options);
	}
}
